﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CFM.API;
using CFM.DTO;
using CFM.Common;
using System.Text.RegularExpressions;

namespace CFM
{
    public partial class frmProduct : Form
    {
        private CategoriesAPI _apiCate = null;
        private ProductAPI _apiPro = null;
        private UnitAPI _apiUnit = null;
        public frmProduct()
        {
            InitializeComponent();
            _apiCate = new CategoriesAPI();
            _apiPro = new ProductAPI();
            _apiUnit = new UnitAPI();
        }

        private void frmProduct_Load(object sender, EventArgs e)
        {
            EnableControl(false);

            btnSave.Enabled = false;
            btnProcess.Enabled = false;
            btnEdit.Enabled = false;
            btnDelete.Enabled = false;
            LoadcbxUnit();
            LoadCbxProductGroup();

        }

        private void LoadCbxProductGroup()
        {
            List<Categories> cate1s = new List<Categories>();
            var groups = _apiCate.GetAll();            
            cate1s.Add(new Categories() { CategoryId = "-1", CategoryName = "--Chọn loại--" });
            cate1s.AddRange(groups);
            cbxProductGroup.DataSource = cate1s;
            cbxProductGroup.DisplayMember = "CategoryName";
            cbxProductGroup.ValueMember = "CategoryId";
            cbxProductGroup.SelectedValue = "-1";

            List<Categories> cate2s = new List<Categories>();            
            cate2s.Add(new Categories() { CategoryId = "-1", CategoryName = "--Chọn loại--" });
            cate2s.AddRange(groups);                        
            cbxCate.DataSource = cate2s;
            cbxCate.DisplayMember = "CategoryName";
            cbxCate.ValueMember = "CategoryId";
            cbxCate.SelectedValue = "-1";
        }
        private void LoadcbxUnit()
        {
            Unit unit = new Unit() { UnitId = "-1", UnitName = "--Chọn đơn vị--" };
            List<Unit> unit1s = new List<Unit>();
            unit1s.Add(unit);
            unit1s.AddRange(_apiUnit.GetAll());    
            cbxUnit1.DataSource = unit1s;
            cbxUnit1.DisplayMember = "UnitName";
            cbxUnit1.ValueMember = "UnitId";
            cbxUnit1.SelectedValue = "-1";
            
            List<Unit> unit2s = new List<Unit>();
            unit2s.Add(unit);
            unit2s.AddRange(_apiUnit.GetAll());    
            cbxUnit2.DataSource = unit2s;
            cbxUnit2.DisplayMember = "UnitName";
            cbxUnit2.ValueMember = "UnitId";
            cbxUnit2.SelectedValue = "-1";
        }
        private void cbxProductGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            string groupProductId = cbxProductGroup.SelectedValue.ToString();
            if (groupProductId == "-1")
                grvProduct.DataSource = _apiPro.GetAll();
            else
                grvProduct.DataSource = _apiPro.GetProductByGroupId(groupProductId);
        }

        private void EnableControl(bool flag)
        {
            txtProductName.Enabled = flag;
            txtProductId.Enabled = flag;
            txtBuyPrice.Enabled = flag;
            txtSalePrice.Enabled = flag;
            txtDescription.Enabled = flag;
            txtRate.Enabled = flag;
            txtQuantity.Enabled = flag;
            cbxCate.Enabled = flag;
            cbxUnit1.Enabled = flag;
            cbxUnit2.Enabled = flag;
        }

        private void ResetControl()
        {


            txtProductName.Text = string.Empty;
            txtProductId.Text = string.Empty;                      
            txtRate.Text = string.Empty;
            txtQuantity.Text = string.Empty;
            txtBuyPrice.Text = string.Empty;
            txtSalePrice.Text = string.Empty;
            txtDescription.Text = string.Empty;
            txtProductName.Focus();
            btnSave.Enabled = false;
            btnProcess.Enabled = false;
            btnDelete.Enabled = true;
            btnEdit.Enabled = true;

            cbxCate.SelectedValue = "-1";
            cbxUnit1.SelectedValue = "-1";
            cbxUnit2.SelectedValue = "-1";

            MethodHelper.ClearErrorProvider();
        }

        private void grvProduct_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;
            Product product = grvProduct.Rows[e.RowIndex].DataBoundItem as Product;
            txtProductName.Text = product.ProductName;
            txtProductId.Text = product.ProductId;
            txtBuyPrice.Text = product.BuyPrice.ToString();
            txtSalePrice.Text = product.SalePrice.ToString();
            txtDescription.Text = product.Description;
            txtRate.Text = product.Rate.ToString();
            txtQuantity.Text = product.Quantity.ToString();
            cbxCate.SelectedValue = product.CategoryId.Trim();
            cbxUnit1.SelectedValue = product.Unit1Id.Trim();
            cbxUnit2.SelectedValue = product.Unit2Id.Trim();
            EnableControl(false);
            MethodHelper.ClearErrorProvider();

            btnEdit.Enabled = true;
            btnDelete.Enabled = true;
            btnSave.Enabled = false;
            btnProcess.Enabled = true;
        }


        private void btnAdd_Click(object sender, EventArgs e)
        {
            EnableControl(true);
            ResetControl();

            btnEdit.Enabled = false;
            btnDelete.Enabled = false;
            btnSave.Enabled = true;
            //chua them ham save ma
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (txtProductId.Text.Length > 0)
            {
                EnableControl(true);
                txtProductId.Enabled = false;
                MethodHelper.ClearErrorProvider();

                btnSave.Enabled = true;
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!CheckBeforeSave())
                return;
            Product prod = new Product();
            prod.ProductId = txtProductId.Text;
            prod.ProductName = txtProductName.Text;
            if(txtQuantity.Text.Trim().Length > 0)
                prod.Quantity =Convert.ToDouble(txtQuantity.Text);
            if(txtRate.Text.Trim().Length > 0)
                prod.Rate = Convert.ToDouble(txtRate.Text);
            if(txtSalePrice.Text.Trim().Length > 0)
                prod.SalePrice = Convert.ToDouble(txtSalePrice.Text);
            if(txtBuyPrice.Text.Trim().Length > 0)
                prod.BuyPrice = Convert.ToDouble(txtBuyPrice.Text);
            prod.Description = txtDescription.Text;
            prod.CategoryId = Convert.ToString(cbxCate.SelectedValue);
            prod.Unit1Id = Convert.ToString(cbxUnit1.SelectedValue);           
            prod.Unit2Id = Convert.ToString(cbxUnit2.SelectedValue);
            if (prod.Unit1Id != "-1" && prod.Unit2Id == "-1")
            {
                prod.Unit2Id = prod.Unit1Id;
                prod.Rate = 1;
            }
            prod.UpdateTime = DateTime.Now;
            bool result = true;
            if (txtProductId.Enabled)
                result = _apiPro.Create(prod);
            else
                result = _apiPro.Update(prod);
            if (!result)
            {
                MessageBox.Show("Lưu không thành công! \nLỗi : " + _apiPro.error, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);                
            }
            else
            {
                MessageBox.Show("Lưu thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LoadCbxProductGroup();
                ResetControl();
                MethodHelper.ClearErrorProvider();

                btnDelete.Enabled = false;
                btnEdit.Enabled = false;
                btnProcess.Enabled = false;
                btnAdd_Click(btnAdd, e);
            }
            
        }
        private void btnDelete_Click_1(object sender, EventArgs e)
        {
            if (txtProductId.Text.Length > 0)
            {
               bool rs =  _apiPro.Delete(txtProductId.Text.Trim());
               if (!rs)
               {
                   MessageBox.Show("Xóa không thành công! \nLỗi : " + _apiPro.error, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);                
               }
               else
               {
                   MessageBox.Show("Xóa thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                   ResetControl();
                   LoadCbxProductGroup();
                   btnEdit.Enabled = false;
                   btnDelete.Enabled = false;
                   btnProcess.Enabled = false;
               }
            }
        }

     
        private bool CheckBeforeSave()
        {
            bool flag = true;
            if (txtProductName.Enabled && txtProductName.Text.Length == 0)
            {
                MethodHelper.AddErrorProvider(txtProductName, Const.EMPTY_MESSAGE);

                flag = false;
            }
            if (txtProductId.Enabled && txtProductId.Text.Length == 0)
            {
                MethodHelper.AddErrorProvider(txtProductId, Const.EMPTY_MESSAGE);
                flag = false;
            }
            if (cbxCate.Enabled && cbxUnit1.SelectedValue.ToString() == "-1")
            {
                MethodHelper.AddErrorProvider(cbxCate, Const.EMPTY_MESSAGE);
                flag = false;
            }
            if (cbxUnit1.SelectedValue.ToString() == "-1" && cbxUnit2.SelectedValue.ToString() == "-1")
            {
                MethodHelper.AddErrorProvider(cbxUnit1, "Chọn  1 trong 2 đơn vị");
                flag = false;
            }
            if (cbxUnit1.SelectedValue.ToString() != "-1" && cbxUnit2.SelectedValue.ToString() != "-1" && txtRate.Text.Length == 0)
            {
                MethodHelper.AddErrorProvider(txtRate, Const.EMPTY_MESSAGE);
                flag = false;
            }
            if (cbxUnit1.SelectedValue.ToString() != "-1" && cbxUnit2.SelectedValue.ToString() == "-1" && txtSalePrice.Text.Length == 0)
            {
                MethodHelper.AddErrorProvider(txtSalePrice, Const.EMPTY_MESSAGE);
                flag = false;
            }
            if (cbxUnit1.SelectedValue.ToString() == "-1" && cbxUnit2.SelectedValue.ToString() != "-1" && txtBuyPrice.Text.Length == 0)
            {
                MethodHelper.AddErrorProvider(txtBuyPrice, Const.EMPTY_MESSAGE);
                flag = false;
            }
           
            return flag;
        }

        private void txtProductId_TextChanged(object sender, EventArgs e)
        {
           
            if (txtProductId.Enabled == true)
            {
                txtProductId.Text = MethodHelper.GetIdFromName(txtProductId.Text);
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (grvProduct.SelectedRows.Count > 0)
            {
                frmFormulaProcess frm = new frmFormulaProcess();
                frm.CurrentProduct = grvProduct.SelectedRows[0].DataBoundItem as Product;
                frm.ShowDialog();
                string groupProductId = cbxProductGroup.SelectedValue.ToString();
                if (groupProductId == "-1")
                    grvProduct.DataSource = _apiPro.GetAll();
                else
                    grvProduct.DataSource = _apiPro.GetProductByGroupId(groupProductId);
            }
        }
        private void ShowFrom(Form frm)
        {
            frm.StartPosition = FormStartPosition.CenterParent;
            frm.ShowDialog();
        }

        private void txtProductName_KeyUp(object sender, KeyEventArgs e)
        {
            txtProductId.Text = MethodHelper.GetIdFromName(txtProductName.Text.Trim());
        }

        private void txtBuyPrice_KeyPress(object sender, KeyPressEventArgs e)
        {
            MethodHelper.OnlyNumberFloatTextBox(sender as TextBox, e);
        }

        private void txtQuantity_KeyPress(object sender, KeyPressEventArgs e)
        {
            MethodHelper.OnlyNumberIntTextBox(sender as TextBox, e);
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }
        
    }
}
